package com.lgmshare.component.imageloader;

import android.annotation.SuppressLint;
import android.content.Context;

import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.Registry;
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool;
import com.bumptech.glide.load.engine.cache.ExternalPreferredCacheDiskCacheFactory;
import com.bumptech.glide.load.engine.cache.LruResourceCache;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.module.AppGlideModule;
import com.bumptech.glide.request.RequestOptions;

import java.io.InputStream;

/**
 * glide配置实现类
 *
 * @GlideModule 如要实现请在项目中继承并添加注解@GlideModule
 * builde.gradle中添加annotationProcessor viewDependencies.glideProcessor
 */
public class ImageLoaderGlideModule extends AppGlideModule {

    int diskSize = 1024 * 1024 * 30;
    int memorySize = (int) (Runtime.getRuntime().maxMemory()) / 8;  // 取1/8最大内存作为最大缓存

    @SuppressLint("CheckResult")
    @Override
    public void applyOptions(Context context, GlideBuilder builder) {
        // Apply options to the builder here.
        // 定义缓存大小和位置
        builder.setDiskCache(new ExternalPreferredCacheDiskCacheFactory(context, "cache", diskSize)); //sd卡中

        // 自定义内存和图片池大小
        builder.setMemoryCache(new LruResourceCache(memorySize));
        builder.setBitmapPool(new LruBitmapPool(memorySize));

        // 定义图片格式
        RequestOptions options = RequestOptions.formatOf(DecodeFormat.PREFER_RGB_565);
        options.diskCacheStrategy(DiskCacheStrategy.RESOURCE);
        builder.setDefaultRequestOptions(options); // 默认
    }

    @Override
    public void registerComponents(Context context, Glide glide, Registry registry) {
        registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory());
    }

    @Override
    public boolean isManifestParsingEnabled() {
        return false;
    }
}